package com.study.train.common.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.study.train.common.context.LoginMemberContext;
import com.study.train.common.resp.MemberLoginResp;
import com.study.train.common.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @description:
 * @author: ZhangYujie
 * @time: 2025/8/11
 */
@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        log.info("用户token信息:{}", token);
        JSONObject jsonObject = JwtUtil.getJSONObject(token);
        log.info("用户json信息:{}", jsonObject);
        MemberLoginResp bean = JSONUtil.toBean(jsonObject, MemberLoginResp.class);
        LoginMemberContext.setMember(bean);
        log.info("已将用户信息保存到ThreadLocal本地线程中");
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
